import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import { todoAdd } from '../../store/actions/todo'

export default function TodoHeader() {
  const [name, setName] = useState('')
  const dispatch = useDispatch()
  function handleChange(e) {
    setName(e.target.value)
  }

  function handleKeyup(e) {
    if (e.keyCode === 13) {
      if (name.trim().length === 0) return
      dispatch(todoAdd({
        id: Date.now(),
        name,
        done: false
      }))
      setName('')
    }
  }
  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        value={name}
        placeholder="What needs to be done?"
        autoFocus
        onChange={handleChange}
        onKeyUp={handleKeyup}
      />
    </header>
  )
}
